package cn.hesion.bio;
/**
 * ClassName: BIOServer <br/>
 * Description: <br/>
 * date: 2021/1/20 14:34<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: NettyLearn
 * @description: BIO服务器
 * @author: hesion
 * @create: 2021-01-20 14:34
 **/
public class BIOServer {
    public static void main(String[] args) {
        //思路
        //2.如果有客户端链接，就创建一个线程，与之通讯(单独写一个方法)
        try {
            ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

            ServerSocket serverSocket = new ServerSocket(9090);
            System.out.println("服务器启动了");
            while (true){
                //监听，等待客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("连接到了一个客户端");

                //创建一个线程与之通讯
                newCachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        handler(socket);
                    }
                });
            }
        } catch (Exception e) {

        }
    }

    private static void handler(Socket socket) {
        try{
            //线程信息
            System.out.println("线程信息 id="+Thread.currentThread().getId()+" "+"name="+Thread.currentThread().getName());
            // 创建一个1024大小的数组 接受数据
            byte[] bytes = new byte[1024];
            //通过sockt 获取一个输入流
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if(-1 != read){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        }catch (Exception e){
                e.printStackTrace();
        }finally {
            System.out.println("关闭Client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
